



import grails.converters.*
class UserController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def show = {
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
           // redirect(action:list)
        }
        else { render userInstance as JSON }
    }

    def delete = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            try {
                userInstance.delete(flush:true)
                flash.message = "User ${params.id} deleted"
                render true
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "User ${params.id} could not be deleted"
                render false;
            }
        }
        else {
        	render false
        }
    }

    

    def update = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(userInstance.version > version) {
                    
                    userInstance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing.")
                    render false
                }
            }
            userInstance.properties = params
            if(!userInstance.hasErrors() && userInstance.save()) {
                flash.message = "User ${params.id} updated"
                render true
            }
            else {
                render false
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            	render false
        }
    }

    def save = {
        def userInstance = new User(params)
     
        if(!userInstance.hasErrors() && userInstance.save()) {
          
            render userInstance.id
        }
        else {
            render userInstance.id
        }
    }
    
    def jsonList = {
		int count = 0;
		params.sort = params.sidx
		params.order = params.sord
		params.max = Math.min( params.rows ? params.rows.toInteger() : 10, 100)
        params.page = params.page ? params.page : 1
        int firstRow = params.max.toInteger() * (params.page.toInteger() - 1)
		def criteria = User.createCriteria()
		def result = criteria{
			and {
				if (params._search && params._search.equals("true")) {
					if (params.searchOper.equals("eq")) {
						eq(params.searchField, params.searchString)
					}
					else
						like(params.searchField, '%' + params.searchString + '%')
				}
				for (Object key: params.keySet()) {
					if (key.toString().endsWith("_mask") && !"".equals(params.get(key))) {
						String field = key.toString().split("_mask")[0]
						eq(field, params.get(key))
					}
				}
				//Paging
                firstResult(firstRow)
                maxResults(params.max)				
				
				//Sorting
                if(!params.sort){
                    params.sort = "id"
                }
                if(!params.order){
                    params.order = "desc"
                }
                order(params.sort, params.order)				
			}
		}
		
		if(result.size()==0){
			flash.message = "${message(code : 'default.norecord.found')}"
		}
		else{
			flash.message = ""
				//Result Count
			def criteria4Count = User.createCriteria()
			count = criteria4Count.get{
				and {
					if (params._search && params._search.equals("true")) {
						if (params.searchOper.equals("eq"))
							eq(params.searchField, params.searchString)
						else
							like(params.searchField, '%' + params.searchString + '%')
				}
				}
				projections { 
					rowCount() 
				}    
			}
		}		
		int totalPages = (count - 1) / params.max.toInteger() + 1
		
		def userInstanceList = result.collect{[cell:[
																        it.id,
				                                                        		
																        it.username,
				                                                        		
																        it.userRealName,
				                                                        		
																        it.passwd,
				                                                        		
																        it.enabled,
				                                                        		
																        it.authorities,
				                                                        		
																        it.description,
				                                                        		
																        it.email,
				                                                        		
																        it.emailShow,
				                                                        		
																        it.pass
				                                                        		]]}
		                                               
		
		def jsonuserInstance = ["page": params.page.toInteger(), "records": count, rows:userInstanceList, "total":totalPages]
		render jsonuserInstance as JSON
	}
    
}
